package models

import (
	"errors"
	"gorm.io/gorm"
	"log"
	"project/jwt-prac/db"
)

type UserRegister struct {
	Username string `form:"username" binding:"required,max=20,printascii,validateUsername"`
	Password string `form:"password" binding:"required,min=8,max=16,excludes= ,printascii,validatePasswd"`
	Email    string `form:"email" binding:"email" binding:"required"`
}

//注册时在数据库中检查用户
func CheckUserRegister(registerSpec UserRegister) (int, error) {
	var (
		userFromDB User
	)
	//判断用户是否已注册
	err := db.DB.Where("username = ?", registerSpec.Username).Take(&userFromDB).Error
	if err == nil {
		return 400, errors.New("该用户名已被注册，请换一个试试")
	} else if err != gorm.ErrRecordNotFound {
		return 500, errors.New("internal server error")
	}

	//判断邮箱是否已注册
	err = db.DB.Where("email = ?", registerSpec.Email).Take(&userFromDB).Error
	if err == nil {
		log.Println("select error")
		return 400, errors.New("该邮箱已被注册，请换个邮箱试试")
	} else if err != gorm.ErrRecordNotFound {
		log.Println("select error")
		return 500, errors.New("internal server error")
	}

	return 200, nil
}
